﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using PhotoPortfolio.Models.Portfolio;

namespace PhotoPortfolio.Controllers
{
    public class HomeController : Controller
    {
        private static readonly string AuthorBlog = ConfigurationManager.AppSettings["AuthorBlog"];
        private static readonly string PhotosVirtualPath = ConfigurationManager.AppSettings["PhotosVirtualPath"];
        private static readonly string DefaultAlbum = ConfigurationManager.AppSettings["DefaultAlbum"];
        private static readonly string DocumentationLocation = ConfigurationSettings.AppSettings["DocumentationLocation"];
        private static readonly string ExcludeDefaultAlbum = "App_Data";

        public ActionResult Index(string album)
        {
            var mobile = Request.Browser.IsMobileDevice;
            var m = BuildModel(album, mobile);
            return View(m);
        }

        public ActionResult SendRequest()
        {
            var m = BuildModel(null, false);
            return View(m);
        }

        public ActionResult SendMail(PortfolioViewModel model)
        {
            if (string.IsNullOrEmpty(model.Message))
            {
                model.Message = "Пусто";
            }

            var email = "admin@sashapotapkin.com";
            var addressAdmin = "mshatikhin@gmail.com";

            var password = "thangie6N";

            var loginInfo = new NetworkCredential(email, password);
            var msg = new MailMessage();
            var smtpClient = new SmtpClient("sashapotapkin.com", 25);


            msg.From = new MailAddress(email);
            msg.To.Add(new MailAddress(email));

            msg.Bcc.Add(new MailAddress(addressAdmin));

            msg.Subject = "Письмо с сайта sashapotapkin.com";
            msg.Body = model.Message;
            msg.IsBodyHtml = true;

            smtpClient.EnableSsl = false;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = loginInfo;
            smtpClient.Send(msg);

            return RedirectToAction("Index", "Home");
        }

        private PortfolioViewModel BuildModel(string album, bool mobile)
        {
            var directoryName = album.IsNullOrWhiteSpace() ? DefaultAlbum : album;
            if (directoryName != null)
            {
                var mapPath = Server.MapPath(PhotosVirtualPath);
                var dir = new DirectoryInfo(mapPath);
                if (dir.Exists)
                {
                    var listDirectories = dir.GetDirectories();
                    var menuLinks = listDirectories.Where(d => d.Name != ExcludeDefaultAlbum).Select(d => d.Name).ToArray();
                    var temp = "";
                    var p = Path.Combine(mapPath, directoryName);
                    var dird = new DirectoryInfo(p);
                    if (dird.Exists)
                    {
                        var fileList = dird.GetFiles();
                        var photoMs = new PhotoM[] { };
                        if (fileList.Length > 0)
                        {
                            var fileList64 = fileList.Where(f => f.Name.Contains("-64.jpg")).OrderBy(f => f.Name).ToArray();
                            var fileList240 = fileList.Where(f => f.Name.Contains("-240.jpg")).OrderBy(f => f.Name).ToArray();
                            var fileList800 = fileList.Where(f => f.Name.Contains("-800.jpg")).OrderBy(f => f.Name).ToArray();
                            var fileList1080 = fileList.Where(f => f.Name.Contains("-1080.jpg")).OrderBy(f => f.Name).ToArray();

                            if (mobile)
                            {
                                if (fileList800.Length > 0)
                                {
                                    photoMs = fileList800.Length == fileList64.Length ?
                                        BuildPhotoMs(fileList800, directoryName, fileList64) :
                                        BuildPhotoMs(fileList800, directoryName);
                                }
                                else
                                {
                                    photoMs = BuildPhotoMs(fileList, directoryName);
                                }
                            }
                            else
                            {
                                if (fileList800.Length > 0)
                                {
                                    if ((fileList800.Length == fileList1080.Length) &&
                                        (fileList800.Length == fileList64.Length))
                                    {
                                        photoMs = BuildPhotoMs(fileList1080, directoryName, fileList64);
                                    }
                                    else
                                    {
                                        photoMs = BuildPhotoMs(fileList800, directoryName);
                                    }
                                }
                                else
                                {
                                    photoMs = BuildPhotoMs(fileList, directoryName);
                                }
                            }
                        }
                        temp = string.Format("mobile:{0}", mobile);
                        var model = new PortfolioViewModel
                        {
                            Temp = temp,
                            MenuLinks = menuLinks,
                            AuthorBlog = AuthorBlog,
                            Album = new AlbumM
                            {
                                Photos = photoMs
                            }
                        };
                        return model;
                    }
                }
            }
            return new PortfolioViewModel
            {
                AuthorBlog = AuthorBlog
            };
        }

        private static PhotoM[] BuildPhotoMs(IEnumerable<FileInfo> fileList, string directoryName)
        {
            return fileList
                .OrderBy(f => f.Name)
                .Select((f, idx) => new PhotoM
                {
                    ImageUrl = BuildImageUrl(directoryName, f),
                    ImageFullUrl = BuildImageUrl(directoryName, f),
                    ImageThumbUrl = BuildImageUrl(directoryName, f)
                })
                .ToArray();
        }

        private static PhotoM[] BuildPhotoMs(IEnumerable<FileInfo> filelist, string directoryName, FileInfo[] fileList64)
        {
            var fileInfos = filelist as FileInfo[] ?? filelist.ToArray();
            return fileInfos
                .OrderBy(f => f.Name)
                .ToArray()
                .Select((f, idx) => new PhotoM
                {
                    ImageUrl = BuildImageUrl(directoryName, f),
                    ImageFullUrl = BuildImageUrl(directoryName, f),
                    ImageThumbUrl = BuildImageUrl(directoryName, fileList64[idx])
                }).ToArray();

        }

        private static string BuildImageUrl(string directoryName, FileInfo f)
        {
            var buildImageUrl = string.Format("{0}/{1}", directoryName, f);
            return buildImageUrl;
        }

        public ActionResult Contact()
        {
            var m = BuildModel(null, false);
            return View(m);
        }
    }
}